package org.spring.springboot.app.file.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.spring.springboot.app.sys.area.service.ISysAreaService;
import org.spring.springboot.app.base.R;
import org.spring.springboot.app.file.domain.vo.FileVO;
import org.spring.springboot.util.ApiIndex;
import org.spring.springboot.util.IdGen;
import org.spring.springboot.util.http.HttpAPIService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.*;

@Api(description="文件操作接口",tags = ApiIndex.SysFileController)
@RestController
public class SysFileController {

    @Autowired
    private ISysAreaService sysAreaService;

    @Resource
    private HttpAPIService httpAPIService;

    @Value("${file.url}")
    private String fileUrl;

    @Value("${file.appid}")
    private String fileAppId;




    @PostMapping(value = "/upload")
    @ResponseBody
    @Transactional
    public R<FileVO> upload(
            @ApiParam(value = "文件", required = true) @RequestParam("file") MultipartFile file,
            @ApiParam(value = "文件目录 例如 user/head/", required = true) @RequestParam(defaultValue = "") String path,
            @ApiParam(value = "文件名称 例如 uuid.jpg", required = true) @RequestParam(defaultValue = "") String name
    ) throws Exception {
        R r = new R();
        FileVO fileVO = new FileVO();
        if (file.isEmpty()) {
            return r.fail().setMessage("文件为空");
        }
        String fileName = IdGen.uuid();
        String[] fileDivisionStr = file.getOriginalFilename().split("\\.");
        final String remote_url = fileUrl+"/upload";// 第三方服务器请求地址
        Calendar now = Calendar.getInstance();
        DecimalFormat dfInt=new DecimalFormat("00");
        String ret = httpAPIService.postFile(file, remote_url, fileAppId,
                path + "/" + now.get(Calendar.YEAR) + "/" +  dfInt.format(now.get(Calendar.MONTH) + 1) + (dfInt.format(now.get(Calendar.DAY_OF_MONTH) )+"") ,
                fileName + "." + fileDivisionStr[fileDivisionStr.length-1]);
        ObjectMapper mapper = new ObjectMapper();
        Map map = mapper.readValue(ret, Map.class);
        String fullpath = (String)((HashMap<String,Object>)map.get("data")).get("fullPath");

        fileVO.setPath(fullpath);
        fileVO.setFullPath(fileUrl + "/file/" +fullpath );
        r.setData(fileVO);
        return r;
    }


    @RequestMapping(value = "/file/**", method = RequestMethod.GET)
    public void file(
            @ApiParam(value = "request", hidden = true) HttpServletRequest request,
            @ApiParam(value = "response", hidden = true) HttpServletResponse response,
            @ApiParam(value = "查询字符串",hidden = false ) @RequestParam(required = false) String process
    ) throws Exception {
        String path = request.getServletPath();
        String fullPath = path.substring("/file/".length(), path.length());
        R r = new R();
        if (StringUtils.isBlank(fullPath)) {
            throw new Exception("文件路径格式错误");
        }
        final String remote_url = fileUrl+"/file/" + fileAppId +"/"+ fullPath;// 第三方服务器请求地址
        httpAPIService.getFile(remote_url,"xxx");
    }



    @RequestMapping(value = "/file/getTwoDimension", method = RequestMethod.GET)
    public void getTwoDimension(
                                @ApiParam(value = "request", hidden = true) HttpServletRequest request,
                                @ApiParam(value = "response", hidden = true) HttpServletResponse response,
                                @ApiParam(value = "二维码地址", required = true) @RequestParam(defaultValue = "")  String url,
                                @ApiParam(value = "二维码宽度", required = false) @RequestParam(defaultValue = "200")  int width,
                                @ApiParam(value = "二维码高度", required = false) @RequestParam(defaultValue = "200")  int height) throws IOException {
        if (url != null && !"".equals(url)) {
            ServletOutputStream stream = null;
            try {
                Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
                hints.put(EncodeHintType.MARGIN,1);
                stream = response.getOutputStream();
                QRCodeWriter writer = new QRCodeWriter();
                BitMatrix m = writer.encode(url, BarcodeFormat.QR_CODE, height, width ,hints );
                MatrixToImageWriter.writeToStream(m, "png", stream);
            } catch (WriterException e) {
                e.printStackTrace();;
            } finally {
                if (stream != null) {
                    stream.flush();
                    stream.close();
                }
            }
        }
    }
}
